<?php
namespace App\utils;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Log;
use Monolog\Logger;

/**
 * Created by PhpStorm.
 * User: air
 * Date: 18-10-12
 * Time: 下午4:29
 */

final class Api{
    private static $_code;
    private static $_msg;

    /**
     * @return mixed
     */
    public static function getCode()
    {
        return self::$_code;
    }

    /**
     * @return mixed
     */
    public static function getMsg()
    {
        return self::$_msg;
    }


    /**
     * 根据邮箱和密码获取token
     * @param $email
     * @param $password
     * @return mixed
     */
    public static  function getApiTokenByEmailAndPassword( $email, $password){
        try{
            $http = new \GuzzleHttp\Client;
            $response = $http->post(API_URL.'oauth/token', [
                'form_params' => [
                    'grant_type' => 'password',
                    'client_id' => 4,
                    'client_secret' => 'hdh79bHRJfg7SOOlXmMdBd1kVOLm2r3fxMnZRJp8',
                    'username' => $email,
                    'password' => $password,
                    'scope' => '*',
                ],
            ]);
            return self::response(json_decode((string) $response->getBody(), true));
        }catch (ClientException $e){
            self::log($e->getMessage());
            return self::response("",101);
        }

    }


    /**
     * 接口统一返回格式
     * @param array $data
     * @param int $code
     * @param string $msg
     * @return mixed
     */
    public static function response($data = null, $code = 1,$msg='')
    {
        if(!$data){
            $data=null;
        }
        self::$_code = $code;
        self::$_msg = config('apiResCode.'.$code).$msg;
        $resData['data'] = $data;
        $resData['code'] = $code;
        $resData['msg'] =  self::$_msg;
        return response($resData);
    }


    /**
     * 写入日志文件
     * @param array $msg
     * @param string $path
     * @param string $fileName
     */
    public static function log($msg=array(),$path='logs/api',$fileName='airLog'){
        $data['msg']=$msg;
        $data['ip']=CommonUtils::get_ip();
        $data['time']=date('Y-m-d H:i:s');

        $newPath=$path.'/'.date('Y-m');
        $newFileName=date("Y-m-d-").$fileName.'.txt';
        FileUtils::makeDirectory($newPath);
        FileUtils::prepend(storage_path($newPath.'/'.$newFileName),print_r($data,true));
    }


}